package com.lagou.edu.service.impl;

import com.lagou.edu.dao.TokenRepository;
import com.lagou.edu.dao.UserRepository;
import com.lagou.edu.pojo.Token;
import com.lagou.edu.pojo.User;
import com.lagou.edu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private TokenRepository tokenRepository;

    @Override
    @Transactional
    public User findByEmail(String email) {
        return userRepository.findByEmail(email);
    }

    @Override
    @Transactional
    public void save(User user) {
        userRepository.save(user);
    }

    @Override
    @Transactional
    public String login(String email, String password) {
        User userExists = userRepository.findByEmail(email);
        if (userExists == null) {
            return "1";
        }

        if (!password.equals(userExists.getPassword())) {
            return "2";
        }

        String uuid = UUID.randomUUID().toString();

        Token tokenExists = tokenRepository.findByEmail(email);
        if (tokenExists != null) {
            tokenExists.setToken(uuid);

            tokenRepository.save(tokenExists);
        }
        else {
            Token token = new Token();
            token.setEmail(email);
            token.setToken(uuid);

            tokenRepository.save(token);
        }

        return uuid;
    }

    @Override
    public Token findByToken(String token) {
        return tokenRepository.findByToken(token);
    }

}
